#encoding=utf-8
import xadmin,ujson,time,datetime,traceback,urllib2,urllib
#新页面不是model对应生成的，菜单url配置中的地址对应register_view的
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView, csrf_protect_m
from xadmin.util import unquote
from django.utils.html import escape
from django import forms
from xadmin.layout import Fieldset, Main, Side, Row, FormHelper
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
from django.views.decorators.debug import sensitive_post_parameters
from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.db.models import Count, Max, F, Q,Min,Sum
import websys.webconfig as webconfig
from django.db import connection
import websys.fun as fun
from  websys.api import InterfaceFun
from cbyx_userdata import getjs
from websys.models import (
    ServerInfo,RankStage,LogRecharge,UserInfo,Recharge_info
)
from  websys import (
    db_redis
)
from websys.api import InterfaceFun,ProtocolHelper
class TestForm(forms.Form):
    """
    A form used to change the password of a user in the admin interface.
    """
    # error_messages = {
    #     'password_mismatch': _("The two password fields didn't match."),
    # }
    # password1 = forms.CharField(label=_("Password"),
    #                             widget=forms.PasswordInput)
    # password2 = forms.CharField(label=_("Password (again)"),
    #                             widget=forms.PasswordInput)

    def __init__(self,  *args, **kwargs):
        #self.user = user
        super(TestForm, self).__init__(*args, **kwargs)

PFINFO_LIST = []
#缓存平台列表
def getPlatformInfo_list():
    global PFINFO_LIST
    if not PFINFO_LIST:
        PFINFO_LIST=ServerInfo.objects.all().values('pf',"name")
getPlatformInfo_list()

recharge_list = []
def getRecharge_list():
    global recharge_list
    recharge_infos=getjs('pay')
    if not recharge_list:
        recharge_dic = recharge_infos['PAY_INFO']
        for i in recharge_dic:
            dics = {}
            dics['id'] = i
            dics['name'] = recharge_dic[i]['name']
            dics['price']=recharge_dic[i]['price']
            recharge_list.append(dics)
        one_gift=recharge_infos['PAY_GIFT_INFO']
        one_dic={}
        one_dic['id']=one_gift['paygift1']['id']
        one_dic['name']='一元礼包'
        one_dic['price']=one_gift['paygift1']['need_money']
        recharge_list.append(one_dic)
        for j in recharge_infos['MONTH_CARD_INFO']:
            dicts={}
            dicts['id']=j
            dicts['name']=recharge_infos['MONTH_CARD_INFO'][j]['name']
            dicts['price'] = recharge_infos['MONTH_CARD_INFO'][j]['price']
            recharge_list.append(dicts)

getRecharge_list()

URL2TITLE={'vague':'模糊查询','info':'详细信息查询&修改','task':'付费任务完成率','system':'系统阶段统计&排行','resource':'资源排行','prop':'道具','recharge_mz':'充值'}

#自定义的页面
URL2DEFINE=['vague','task','system','resource','info','prop','recharge_mz']
#金钻消耗统计页面
class CommonUserView(ModelAdminView):
    model = ServerInfo
    this_form = TestForm
    common_obj={'jstype':'vendor','css_js':('xadmin.form.css','datepicker.css','xadmin.plugins.css', 'xadmin.page.form.js','xadmin.widget.datetime.js')}

    html_obj={}
    for ii in URL2TITLE:
        html_obj[ii]={'title':URL2TITLE[ii]}
        html_obj[ii].update(common_obj)

    @csrf_protect_m
    def get(self, request,_type):
        if not self.has_change_permission(request):
            raise 123#PermissionDenied
        self.obj = {}
        self.form = self.this_form()
        #print _type,'--CommonReportView-'
        self.htmlconfig=self.html_obj[_type]
        _title,_tmpurl=self.htmlconfig['title'],'commonreport.html'
        #if 'isDefine' in self.htmlconfig and self.htmlconfig['isDefine']==1:
        if _type in URL2DEFINE:
            _tmpurl = 'userdata/%s.html' % (_type)
        self.title=_title

        self.tempurl=_tmpurl
        global PFINFO_LIST
        self.htmldata={'type':_type,'apps':PFINFO_LIST}

        global recharge_list
        self.rechargedata = {'lists': recharge_list}

        return self.get_response()

    def get_media(self):
        media = super(CommonUserView, self).get_media()
        if self.htmlconfig['jstype']=='static':
            for ii in self.htmlconfig['css_js']:
                file_type = ii.split('.')[-1]
                if file_type=='css':
                    media.add_css({'screen': [ii]})
                elif file_type=='js':
                    media.add_js((self.static(ii),))
            #tmp_media=self.static(*self.htmlconfig['css_js'])
        else:
            media+=self.vendor(*self.htmlconfig['css_js'])
        media = media+ self.form.media
        return media

    def get_context(self):
        #获取数据
        context = super(CommonUserView, self).get_context()
        #print(context,'-------------------*****get_context*****',)
        helper = FormHelper()
        helper.form_tag = False
        self.form.helper = helper
        context.update({
            #'title': _('Change password: %s') % escape(unicode(self.obj)),
            'form': self.form,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_view_permission': True,
            'original': self.obj,
            #chong add
            'title':self.title,#_('My Information'),
            'account_view':True,
            'serverval':"服务器上的值",
            'htmldata':self.htmldata,
            'rechargedata': self.rechargedata
        })
        return context

    #可以按不同的参数加载对应的页面
    def get_response(self):
        #print(self.get_context(),"----******get_response*******",self.admin_site.name)
        return TemplateResponse(self.request, [self.tempurl] , self.get_context(), current_app=self.admin_site.name)
        #return TemplateResponse(self.request, [ self.change_user_password_template or'xadmin/auth/user/change_password.html']
                               # , self.get_context(), current_app=self.admin_site.name)

#ajax请求页面
urlpatterns = patterns('',
                        #url(r'^detaile', 'websys.view.userdata.op_detaile', name='op_detaile'),
                        url(r'^vague', 'websys.view.userdata.op_vague', name='op_vague'),
                        url(r'^paytask', 'websys.view.userdata.op_task', name='op_task'),
                        url(r'^ranks', 'websys.view.userdata.op_ranks', name='op_ranks'),
                        url(r'^resource', 'websys.view.userdata.op_resource', name='op_resource'),
                        url(r'^prop', 'websys.view.userdata.op_prop', name='op_prop'),
                       url(r'^finduser', 'websys.view.userdata.op_finduser', name='op_finduser'),
                        url(r'^getuser', 'websys.view.userdata.op_getuser', name='op_getuser'),
                       url(r'^saveuser', 'websys.view.userdata.op_saveuser', name='op_saveuser'),
                       url(r'^re_recharges', 'websys.view.userdata.re_recharges', name='re_recharges'),
                        url(r'^qu_recharges', 'websys.view.userdata.qu_recharges', name='qu_recharges'),


                       )

APP_KEY='nhmj_@12345'
import hashlib
#数字签名验证uid=xxx&gameid=xxx&sign=xxxx
def get_sorted_kv_list(param):
    sorted_keys = sorted(param)
    return [(k, param[k]) for k in sorted_keys]
def get_sign(param, ignore_keys=('sign'), app_key=APP_KEY):
    param = {k: str(v) for k, v in param.items() if k not in ignore_keys}
    kv_list = get_sorted_kv_list(param)
    string = "".join(["&".join(["=".join(x) for x in kv_list]), app_key])
    return hashlib.md5(string).hexdigest()

#获取多服务器
def getServers(obj):
    ser_arr=[]
    tmp_arr= obj.server.all()
    print '----------------',tmp_arr
    for ii_item in tmp_arr:
        ser_arr.append( ii_item.pf)
    return ser_arr


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_vague(request):
    obj =[{'server':'127.0.0.1','userid':55,'username':'测试啊','detaile':''},{'server':'192.168.1.138','userid':66,'username':'牛皮啊','detaile':''}]
    return HttpResponse(ujson.dumps(obj))

#根据呢称查找用户数据?name=xxxxxxxxx&sid=xx
#u'user_list': [{u'name': u'\u7687\u96c5\u5bb9', u'uid': u'73ead9c4a39411e7950a5254000d335c'}]
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_finduser(request):
    _name = request.GET["name"]
    _sid = request.GET["sid"]
    t_arr=[]
    obj =InterfaceFun.SEARCH_NAME(_sid,_name)
    if obj['code']==0:
        for ii_item in obj['res']['user_list']:
            t_arr.append({'userid':ii_item['uid'],'username':ii_item['name'],'detaile':''})
    return HttpResponse(ujson.dumps(t_arr))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_task(request):
    print '-----------------1----------'
    obj =[{'taskid':25,'finish_number':55,'finish_rate':155},{'taskid':25,'finish_number':55,'finish_rate':155}]
    return HttpResponse(ujson.dumps(obj))





@csrf_exempt
@login_required(login_url="/xadmin/")
def op_resource(request):
    print '-----------------1----------'
    obj =[{'rank':55,'uid':155,'number':15,'username':'测试'},{'rank':55,'uid':155,'number':15,'username':'测试'}]
    return HttpResponse(ujson.dumps(obj))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_ranks(request):
    ret=[]
    #obj =[{'stage':25,'rank':55,'uid':155,'server':15,'username':'测试'},{'stage':25,'rank':55,'uid':155,'server':15,'username':'测试'}]
    #参数
    t_date_0,t_date_1=request.GET["date"].split(',')
    s_id = request.GET["pf"]#服
    s_type = request.GET["typeid"]#类型
    t_date_2=str(t_date_1+' 23:59:59')

    #查询数据
    #t_arr = RankStage.objects.filter(create_time__range=(t_date_0, t_date_1 + ' 23:59:59'), server=s_id, reason=s_type)
    # stage=RankStage.objects.filter(create_time__range=(t_date_0, t_date_1 + ' 23:59:59'), server=s_id, reason=s_type).values('stageid').distinct()
    # #print stage,'----------------------------------s------------',type(stage)
    # time_list=[]
    # for times in stage:
    #     time_list.append(int(times['stageid']))
    # #print time_list,'-------1------'
    # time_lists=sorted(time_list,reverse=True)
    #print time_lists,'=================2============='
    # for each in time_lists[:10]:
        # rank_info=RankStage.objects.filter(create_time__range=(t_date_0, t_date_1 + ' 23:59:59'), server=s_id, reason=s_type).filter(stageid=each).order_by('rankid')[:100]
    t_arr=RankStage.objects.filter(create_time__range=(t_date_0,t_date_1+' 23:59:59'),server=s_id,reason=s_type).order_by('-stageid','rankid')[:500]
    #rank_info=RankStage.objects.raw("select * from websys_rankstage where create_time >=%s AND create_time< %s AND server=%s AND reason=%s ORDER BY stageid DESC ,rankid"%(t_date_0,t_date_1,str(s_id),str(s_type)))[:500]
    for ii_item in t_arr:
        tmp_obj={'stage':fun.StampToTime(ii_item.stageid),'rank':ii_item.rankid,'uid':ii_item.uid,'username':ii_item.name,'score':ii_item.score}
        ret.append(tmp_obj)
    return HttpResponse(ujson.dumps(ret))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_prop(request):
    data = {'ret':-1,'msg':''}
    uid = request.POST['uid']
    server=request.POST['server']
    print '---------',server
    propid =request.POST['propid']
    number =request.POST['number']
    items ={}
    propids = str(propid).split(',')
    numbers = str(number).split(',')
    if len(propids) == len(numbers):
        for i in range(len(propids)):
            items[propids[i]] = int(numbers[i])
    else:
        data['msg'] = '道具id或数量格式错误!'
        data['ret'] = -1
        return HttpResponse(ujson.dumps(data))
    ser_arr = []
    ser_arr.append(server)
    if InterfaceFun.DELITEMS(ser_arr,uid,items) ==0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        data['msg']='删除成功！'
        data['ret'] = 0
    return HttpResponse(ujson.dumps(data))


#查询某个uid的数据?uid=xxxxxxxxx&sid=xx
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_getuser(request):
    _uid = request.POST["uid"]
    _sid = request.POST["sid"]
    obj =InterfaceFun.USER_INFO(_sid,_uid)
    #obj={"res":{"otherInfo":{"MJTB_level":51,"pvp_rank":1,"GGZJ_chapter":20,"friends_num":50,"battle_name":"\u667a\u53d6\u6c49\u4e2d72-2"},"union":{"skills":{"\u751f\u547d":0,"\u95ea\u907f":0,"\u66b4\u51fb":0,"\u72c2\u6012":2,"\u683c\u6321":0}},"bag":[{"num":"1","id":"16100002","name":"\u8340\u5f67"},{"num":"1","id":"21400003","name":"\u5492\u5e08"},{"num":"1","id":"21400002","name":"\u5e55\u50da"},{"num":"1","id":"21400006","name":"\u6b65\u5175\u5b88\u536b"},{"num":"1","id":"21400005","name":"\u67aa\u5175\u5b88\u536b"},{"num":"1","id":"11400003","name":"\u5492\u5e08"},{"num":"1","id":"16200002","name":"\u8bf8\u845b\u4eae"},{"num":"1","id":"16200001","name":"\u5173\u7fbd"},{"num":"2","id":"21000003","name":"\u9ad8\u7ea7\u7ecf\u9a8c\u5361"},{"num":"58","id":"21000002","name":"\u4e2d\u7ea7\u7ecf\u9a8c\u5361"},{"num":"51","id":"21000001","name":"\u666e\u901a\u7ecf\u9a8c\u5361"},{"num":"1","id":"11400006","name":"\u6b65\u5175\u5b88\u536b"},{"num":"1","id":"11400004","name":"\u5f29\u5175\u5b88\u536b"},{"num":"1","id":"11400005","name":"\u67aa\u5175\u5b88\u536b"},{"num":"1","id":"11400002","name":"\u5e55\u50da"},{"num":"1","id":"16300001","name":"\u5b59\u6743"},{"num":"0","id":"24300003","name":"\u5927\u4e54"},{"num":"1","id":"16400001","name":"\u5de6\u6148"},{"num":"1","id":"16400002","name":"\u5415\u5e03"},{"num":"1","id":"21400004","name":"\u5f29\u5175\u5b88\u536b"},{"num":"1","id":"12100002","name":"\u6ee1\u5ba0"},{"num":"1","id":"15200004","name":"\u9ec4\u6708\u82f1"}],"r":0,"userInfo":{"mails":0,"gamePointBuyNum":0,"uid":"604e677ed96c11e7983952540093562e","gold":443,"point":0,"logintips":0,"fightbuynums":8,"energy":4,"days7tips":1,"hasdays7":0,"bossbuynums":0,"vipLv":6,"month":0,"makeupTime":"2017-12-05 11:28:35","exploit":0,"pay_multi":{},"beetle":0,"battle":"60357|1514456785","is_month_card":"\u5426","titlelv":1,"wuhun":1350,"totalRecharge":1184,"nick":"\u666f\u5c0f\u5929","is_year_card":"\u5426","vipGifts":101,"eaddtime":-276.5622360706,"lv":114,"goldpoint":4901,"energyBuyNums":0,"maxBuyNum":400,"GGZJenergy":4,"daytasknums":0,"gamepoint":12008778,"power":[6034049,{"604e677ed96c11e7983952540093562e|-|16100002":618695,"604e677ed96c11e7983952540093562e|-|16200002":967904,"604e677ed96c11e7983952540093562e|-|16200001":1089328,"604e677ed96c11e7983952540093562e|-|16300001":737847,"604e677ed96c11e7983952540093562e|-|16400001":1724528,"604e677ed96c11e7983952540093562e|-|16400002":895747}],"is_get_paygift1":"\u662f","is_buy_CZJJ":"\u662f","is_week_card":"\u662f","tasktips":0,"unionsId":"7b5ba872d96e11e7983952540093562e","lastlogin":"2017-12-28 00:05:58","unionsName":"\u840c\u4e00\u8138\u8840","vipexp":11840,"goldpointMonth":0,"recharge_num":8,"cardshoptips":0,"is_get_all_life_FP_reward":'true',"summon":10,"sqtips":0,"citytips":0,"exp":168717928,"country":"1","contribution":17300,"bossnumsleft":20,"gifttips":0},"cards":[{"lv":70,"train":"1890|0|19273","star":2,"id":"16400001","name":"\u5de6\u6148"},{"lv":53,"train":"760|0|8281","star":2,"id":"16200001","name":"\u5173\u7fbd"},{"lv":36,"train":"","star":2,"id":"16100002","name":"\u8340\u5f67"},{"lv":49,"train":"849|0|9155","star":2,"id":"16200002","name":"\u8bf8\u845b\u4eae"},{"lv":48,"train":"","star":2,"id":"16400002","name":"\u5415\u5e03"},{"lv":43,"train":"","star":2,"id":"16300001","name":"\u5b59\u6743"}],"ZBInfo":{"sq_info":[{"color":4,"lv":2,"id":"1","name":"\u795e\u5668\u00b7\u53e4\u952d\u5200"},{"color":4,"lv":2,"id":"3","name":"\u795e\u5668\u00b7\u7384\u9ec4\u5f13"},{"color":4,"lv":3,"id":"2","name":"\u795e\u5668\u00b7\u9752\u8679\u5251"},{"color":5,"lv":1,"id":"5","name":"\u795e\u5668\u00b7\u9f99\u80c6\u4eae\u94f6\u67aa"},{"color":5,"lv":1,"id":"4","name":"\u795e\u5668\u00b7\u96cc\u96c4\u53cc\u80a1\u5251"},{"color":6,"lv":-1,"id":"7","name":"\u795e\u5668\u00b7\u501a\u5929\u5251"},{"color":5,"lv":-1,"id":"6","name":"\u795e\u5668\u00b7\u4e08\u516b\u86c7\u77db"},{"color":6,"lv":-1,"id":"9","name":"\u795e\u5668\u00b7\u65b9\u5929\u753b\u621f"},{"color":6,"lv":-1,"id":"8","name":"\u795e\u5668\u00b7\u9752\u9f99\u5043\u6708\u5200"}],"zb_info":[{"strengthenLv":40,"name":"\u9f99\u7ffc\u5934\u76d4","power":13000,"color":3,"refineValue":1120,"pos":3,"sid":"80000033","id":"80000033|96dfe4d4e22711e78feb52540093562e"},{"strengthenLv":30,"name":"\u9f99\u7ffc\u67aa\u5203","power":9600,"color":3,"refineValue":710,"pos":2,"sid":"80000031","id":"80000031|96dfde80e22711e78feb52540093562e"},{"strengthenLv":42,"name":"\u9f99\u7ffc\u67aa\u5203","power":18800,"color":3,"refineValue":2250,"pos":3,"sid":"80000031","id":"80000031|4b0def00d9a411e78e8d52540093562e"},{"strengthenLv":40,"name":"\u9f99\u7ffc\u94e0\u7532","power":14600,"color":3,"refineValue":1360,"pos":3,"sid":"80000032","id":"80000032|96dfe9f2e22711e78feb52540093562e"},{"strengthenLv":35,"name":"\u9f99\u7ffc\u8170\u5e26","power":12100,"color":3,"refineValue":980,"pos":0,"sid":"80000034","id":"80000034|5486462ee14011e78feb52540093562e"},{"strengthenLv":31,"name":"\u7834\u519b\u6218\u5203","power":25500,"color":4,"refineValue":1320,"pos":1,"sid":"80000041","id":"80000041|baf97ae4e57711e7bf5b52540093562e"},{"strengthenLv":45,"name":"\u7834\u519b\u6218\u5203","power":34700,"color":4,"refineValue":1970,"pos":0,"sid":"80000041","id":"80000041|889867a6e22811e790a852540093562e"},{"strengthenLv":32,"name":"\u9f99\u7ffc\u94e0\u7532","power":13000,"color":3,"refineValue":1220,"pos":1,"sid":"80000032","id":"80000032|0f1536e2e22911e7ae5652540093562e"},{"strengthenLv":30,"name":"\u9f99\u7ffc\u5934\u76d4","power":12000,"color":3,"refineValue":1080,"pos":4,"sid":"80000033","id":"80000033|32d9a904e7ca11e7ae5652540093562e"},{"strengthenLv":30,"name":"\u9f99\u7ffc\u5934\u76d4","power":14000,"color":3,"refineValue":1470,"pos":2,"sid":"80000033","id":"80000033|1194c64ce5a011e790a852540093562e"},{"strengthenLv":35,"name":"\u9f99\u7ffc\u67aa\u5203","power":10100,"color":3,"refineValue":660,"pos":4,"sid":"80000031","id":"80000031|0c27452ee22911e7869f52540093562e"},{"strengthenLv":40,"name":"\u9f99\u7ffc\u8170\u5e26","power":12600,"color":3,"refineValue":1030,"pos":3,"sid":"80000034","id":"80000034|0f153bf6e22911e7ae5652540093562e"},{"strengthenLv":30,"name":"\u9f99\u7ffc\u8170\u5e26","power":9600,"color":3,"refineValue":660,"pos":1,"sid":"80000034","id":"80000034|96dfeefce22711e78feb52540093562e"},{"strengthenLv":32,"name":"\u9f99\u7ffc\u5934\u76d4","power":13000,"color":3,"refineValue":1200,"pos":1,"sid":"80000033","id":"80000033|0f153246e22911e7ae5652540093562e"},{"strengthenLv":30,"name":"\u9f99\u7ffc\u8170\u5e26","power":9600,"color":3,"refineValue":660,"pos":2,"sid":"80000034","id":"80000034|0f7e1a48e5a011e790a852540093562e"},{"strengthenLv":20,"name":"\u9f99\u7ffc\u8170\u5e26","power":8600,"color":3,"refineValue":660,"pos":5,"sid":"80000034","id":"80000034|5d623d48e95111e7ae5652540093562e"},{"strengthenLv":21,"name":"\u9f99\u7ffc\u94e0\u7532","power":9100,"color":3,"refineValue":720,"pos":5,"sid":"80000032","id":"80000032|0c6e80a0e7ca11e78feb52540093562e"},{"strengthenLv":22,"name":"\u9f99\u7ffc\u67aa\u5203","power":8800,"color":3,"refineValue":710,"pos":5,"sid":"80000031","id":"80000031|0f152cc4e22911e7ae5652540093562e"},{"strengthenLv":30,"name":"\u9f99\u7ffc\u8170\u5e26","power":9600,"color":3,"refineValue":660,"pos":4,"sid":"80000034","id":"80000034|0ab5908ce7ca11e78feb52540093562e"},{"strengthenLv":41,"name":"\u9f99\u7ffc\u94e0\u7532","power":15100,"color":3,"refineValue":1450,"pos":2,"sid":"80000032","id":"80000032|3753999cde6311e79b4952540093562e"},{"strengthenLv":35,"name":"\u7834\u519b\u94e0\u7532","power":34700,"color":4,"refineValue":2460,"pos":0,"sid":"80000042","id":"80000042|95009c82e57711e78d7152540093562e"},{"strengthenLv":21,"name":"\u9f99\u7ffc\u5934\u76d4","power":8700,"color":3,"refineValue":700,"pos":5,"sid":"80000033","id":"80000033|5e13f9fce95111e7ae5652540093562e"},{"strengthenLv":30,"name":"\u9f99\u7ffc\u94e0\u7532","power":11600,"color":3,"refineValue":980,"pos":4,"sid":"80000032","id":"80000032|13b9c954e5a011e790a852540093562e"},{"strengthenLv":35,"name":"\u9f99\u7ffc\u5934\u76d4","power":12100,"color":3,"refineValue":1030,"pos":0,"sid":"80000033","id":"80000033|5c9d32a0dfce11e78feb52540093562e"}]}},"code":0}
    #print obj['res']['userInfo'],'----------------1---------------------------------========'
    obj['res']['userInfo']['makeupTime']=fun.StampToTime(int(obj['res']['userInfo']['makeupTime']))
    obj['res']['userInfo']['lastlogin'] = fun.StampToTime(int(obj['res']['userInfo']['lastlogin']))
    obj['res']['userInfo']['recharge_num'] = LogRecharge.objects.filter(uid=str(obj['res']['userInfo']['uid'])).count()
    key_list=['is_get_paygift1','is_buy_CZJJ','is_week_card','is_month_card','is_year_card']
    obj['res']['ZBInfo']['zb_info'].sort(key=lambda x:x['pos'])
    for i in key_list:
        #print obj['res']['userInfo'][i],'===========================2=====================',type(str(obj['res']['userInfo'][i]))
        if str(obj['res']['userInfo'][i])=='False':
            obj['res']['userInfo'][i]='否'
        else:
            obj['res']['userInfo'][i] = '是'

    return HttpResponse(ujson.dumps(obj))

#保存某个uid的属性数据?uid=xxxxxxxxx&sid=xx&key=xxx&value=xxx
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_saveuser(request):
    _uid = request.POST["uid"]
    _sid = request.POST["sid"]
    obj =InterfaceFun.USER_INFO(_sid,_uid)
    return HttpResponse(ujson.dumps(obj))



@csrf_exempt
@login_required(login_url="/xadmin/")
def re_recharges(request):
    data = {'ret': -1, 'rows': [], 'msg': ''}
    uid = request.POST['uid']
    recharge_info = request.POST['recharge_id']
    server = request.POST['server']
    #server='_5wan1'
    charge_id = str(recharge_info).split(',')[0]
    charge_money = str(recharge_info).split(',')[1]

    url='http://123.207.24.108:8900/_5wanGMPay'#?uid=%s&sid=%s&item=%s&money=%s'%(uid,server,str(charge_id),charge_money)
    values={
        'uid':uid,
        'sid':server,
        'item':charge_id,
        'money':charge_money
    }
    #print url,'-------------url---------'
    url_data=urllib.urlencode(values)
    req=urllib2.Request(url,url_data)
    response=urllib2.urlopen(req)
    page=response.read()
    #page='success'
    change_dic={'paygift1':111}
    other_dict={'month1':222,'month2':333,'month3':444}
    if str(page)!='success':
        data['msg']='充值失败!'
    else:
        charge_info = Recharge_info()
        charge_info.uid=uid+'('+str(server)+')'
        charge_info.charge_moeny=charge_money

        if str(charge_id)=='paygift1':
            charge_info.charge_id = change_dic[str(charge_id)]
        else:
            if str(charge_id) in other_dict:
                charge_info.charge_id = other_dict[str(charge_id)]
            else:
                charge_info.charge_id = int(charge_id)
        charge_info.save()
        data['msg']='充值成功!'
        data['ret']=0
    return HttpResponse(ujson.dumps(data))



@csrf_exempt
@login_required(login_url="/xadmin/")
def qu_recharges(request):
    recharge_info = Recharge_info.objects.all().order_by('-id')
    recharge_dic = getjs('pay')['PAY_INFO']
    recharge_s=[]
    for i in recharge_dic:
        dics = {}
        dics['id'] = i
        dics['name'] = recharge_dic[i]['name']
        dics['price'] = recharge_dic[i]['price']
        recharge_s.append(dics)
    lists =[]
    change_dic = {1:'paygift1'}
    for i in recharge_info:
        info_dicts={}
        info_dicts['uids']=i.uid
        info_dicts['moeny']=i.charge_moeny
        for j in recharge_s:
            if int(i.charge_id)==111:
                info_dicts['charge_id']='一元礼包'
            elif int(i.charge_id)==222:
                info_dicts['charge_id']='周卡'
            elif int(i.charge_id)==333:
                info_dicts['charge_id']='月卡'
            elif int(i.charge_id)==444:
                info_dicts['charge_id']='年卡'
            else:
                if int(i.charge_id)==int(j['id']):
                    info_dicts['charge_id']=j['name']
        info_dicts['times']=str(i.create_time)
        lists.append(info_dicts)
    return HttpResponse(ujson.dumps(lists))


#渲染注册请求页面,url配置
# xadmin.site.register_view(r'^core/$', CommonReportView,name='core_report')#核心数据
# xadmin.site.register_view(r'^recharge/$', CommonReportView,name='recharge_report')
# xadmin.site.register_view(r'^online/$', CommonReportView,name='online_report')
# xadmin.site.register_view(r'^props/$', CommonReportView,name='props_report')
# xadmin.site.register_view(r'^newloss/$', CommonReportView,name='newloss_report')
# xadmin.site.register_view(r'^loadloss/$', CommonReportView,name='loadloss_report')
xadmin.site.register_view(r'^userdata/(.+)/$', CommonUserView,name='user_%s')#各种按日，月，年汇总页面
